import React, { useState, useRef, useEffect } from 'react';
import { Toast, NavBar, Button } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

export default function Ren() {
    const navigate = useNavigate()
    useEffect(() => {
        startCamera();
    }, []);
    const videoRef = useRef(null);
    const canvasRef = useRef(null);
    const [capturedImages, setCapturedImages] = useState([]);
    const startCamera = async () => {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        videoRef.current.srcObject = stream;
    };
    const capture = () => {
        const canvas = canvasRef.current;
        const context = canvas.getContext('2d');
        context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);
        const imageSrc = canvas.toDataURL('image/jpeg');
        setCapturedImages([...capturedImages, imageSrc])
        submitImages(imageSrc)
    };
    let submitImages = async (img) => {
        let data = await axios.post('http://localhost:3000/face', { b64: img })
        if (data.data.code === 200) {
            Toast('验证成功')
            localStorage.setItem('Token','123')
            navigate('/setup')
        } else {
            Toast(data.data.msg)
        }
    };

    // 导航头回退
    let headgo = () => {
        navigate('/Setup')
    }
    return (
        <div id='faceLogin'>
            {/* 导航头 */}
            <div className='header'>
                <NavBar
                    title={<h2>人脸验证</h2>}
                    onClickLeft={() => { headgo() }}
                    onClickRight={() => Toast('按钮')}
                />
            </div>
            <div id='faceLogin_video'>
                <video ref={videoRef} autoPlay />
            </div>
            <canvas ref={canvasRef} style={{ display: 'none' }} />
            <div id='button'>
                <Button type='primary' onClick={() => { capture() }}>
                    验证
                </Button>
            </div>
            {/* fotter */}
            <div id='fotter'>
                {/* <Loginfotter /> */}
            </div>
        </div>
    )
}
